/**
 * 用户模型
 *
 * 主要功能：
 * - 用户注册
 * - 用户登录
 *
 * @file user.js
 * @version 1.0.0
 * @author "nailuo"
 * @created 2025-8-30
 * @lastModified 2025-8-30
 */

const { pool } = require("../connection.js");

// 用户注册
const registerUser = async (username, password, email) => {
    try {
        const sql = "INSERT INTO users (username, password, email) VALUES (?, ?, ?)";
        const [result] = await pool.execute(sql, [username, password, email]);
        if (!result.affectedRows) {
            throw new Error('用户注册失败');
        }
        console.log('✅ 用户注册成功');
        return result;
    } catch (error) {
        console.error('❌ 用户注册失败:', error.message);
        throw error;
    }
};

// 用户登录
const loginUser = async (username, password) => {
    try {
        const sql = "SELECT * FROM users WHERE username = ? AND password = ?";
        const [rows] = await pool.execute(sql, [username, password]);
        if (!rows[0]) {
            throw new Error('用户不存在，请检查用户名和密码');
        }
        console.log('✅ 用户登录成功');
        return rows[0];
    } catch (error) {
        console.error('❌ 用户登录失败:', error.message);
        throw error;
    }
};

// 导出用户模型
module.exports = {
    registerUser,
    loginUser,
};
